﻿using System;
using System.Collections.Generic;
 using UnityEngine;
using System.Text;

/// <summary>
/// 状态管理类
/// </summary>
public class SoldierFSMSystem
{
    /// <summary>
    /// 状态集合
    /// </summary>
    private List<ISoldierState> mStates;
     /// <summary>
     /// 当前状态
     /// </summary>
    private ISoldierState mCurrentState;

    public ISoldierState currentState {
        get { return mCurrentState; }
    }

    /// <summary>
    /// 添加状态
    /// </summary>
    /// <param name="state"></param>
    public void AddState(ISoldierState state)
    {
        if (state == null)
        {
            Debug.LogError("要添加的状态不能为空"); return;
        }
        if (mStates.Count == 0)
        {
            mStates.Add(state);
            mCurrentState = state;
            return;
        }
        foreach (ISoldierState s in mStates)
        {
            if (s.stateID == state.stateID)
            {
                Debug.LogError("要添加的状态ID["+s.stateID+"]已经添加过了");return;
            }
        }
        mStates.Add(state);
    }

    public void AddState(params ISoldierState[] states)
    {
        foreach (ISoldierState s in states)
        {
            AddState(s);
        }
    }

    /// <summary>
    /// 删除状态
    /// </summary>
    /// <param name="stateID"></param>
    public void DeleteState(SoldierStateID stateID)
    {
        if (stateID == SoldierStateID.NullState)
        {
            Debug.LogError("要删除的状态ID[" + stateID + "]为空"); return;
        }
        foreach (ISoldierState s in mStates)
        {
            if (s.stateID == stateID)
            {
                mStates.Remove(s);return;
            }
        }
        Debug.LogError("要删除的状态ID[" + stateID + "]不存在于集合中"); ;
    }

    /// <summary>
    /// 执行转换条件
    /// </summary>
    /// <param name="trans"></param>
    public void PerformTransition(SoldierTransition trans)
    {
        if (trans == SoldierTransition.NullTransition)
        {
            Debug.LogError("要执行的转换条件为空:"+trans);return;
        }
        SoldierStateID nextStateID = mCurrentState.GetOutPutState(trans);
        if(nextStateID == SoldierStateID.NullState)
        {
            Debug.LogError("在转换条件[" + trans+"]下,没有对应的转换状态"); return;
        }
        foreach (ISoldierState  s in mStates)
        {
            if (s.stateID == nextStateID)
            {
                 //由当前状态转换为下一个状态
                mCurrentState.DoBeforeLeaving();
                mCurrentState = s;
                mCurrentState.DoBeforeEntering();
                return; 
            }
        }
    }

}
